import React, { useEffect, useState } from 'react';
import {
  Table,
  Tag,
  Space,
  Button,
  Modal,
  Form,
  Select,
  message,
  Input,
} from 'antd';
import { EditOutlined, EyeOutlined } from '@ant-design/icons';
import { orders } from '../services/api';

interface Order {
  id: string;
  orderNumber: string;
  customer: string;
  totalAmount: number;
  status: string;
  createTime: string;
  items: OrderItem[];
}

interface OrderItem {
  productId: string;
  productName: string;
  quantity: number;
  price: number;
}

const OrderManagement: React.FC = () => {
  const [orderList, setOrderList] = useState<Order[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    try {
      const response = await orders.getAll();
      setOrderList(response.data);
    } catch (error) {
      message.error('获取订单列表失败！');
    }
  };

  const handleView = (record: Order) => {
    setSelectedOrder(record);
    setIsModalVisible(true);
  };

  const handleStatusChange = async (values: { status: string }) => {
    if (!selectedOrder) return;

    try {
      await orders.update(selectedOrder.id, values);
      message.success('更新成功！');
      setIsModalVisible(false);
      fetchOrders();
    } catch (error) {
      message.error('更新失败！');
    }
  };

  const getStatusColor = (status: string) => {
    const statusMap: { [key: string]: string } = {
      pending: 'warning',
      processing: 'processing',
      shipped: 'success',
      delivered: 'success',
      cancelled: 'error',
    };
    return statusMap[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const statusMap: { [key: string]: string } = {
      pending: '待处理',
      processing: '处理中',
      shipped: '已发货',
      delivered: '已送达',
      cancelled: '已取消',
    };
    return statusMap[status] || status;
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
    },
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Order) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleView(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Table columns={columns} dataSource={orderList} rowKey="id" />

      <Modal
        title="订单详情"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedOrder && (
          <div>
            <Form
              form={form}
              layout="vertical"
              initialValues={{ status: selectedOrder.status }}
              onFinish={handleStatusChange}
            >
              <Form.Item
                name="status"
                label="订单状态"
                rules={[{ required: true, message: '请选择订单状态！' }]}
              >
                <Select>
                  <Select.Option value="pending">待处理</Select.Option>
                  <Select.Option value="processing">处理中</Select.Option>
                  <Select.Option value="shipped">已发货</Select.Option>
                  <Select.Option value="delivered">已送达</Select.Option>
                  <Select.Option value="cancelled">已取消</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit">
                  更新状态
                </Button>
              </Form.Item>
            </Form>

            <div style={{ marginTop: 24 }}>
              <h3>订单信息</h3>
              <p>订单号：{selectedOrder.orderNumber}</p>
              <p>客户：{selectedOrder.customer}</p>
              <p>总金额：¥{selectedOrder.totalAmount.toFixed(2)}</p>
              <p>创建时间：{selectedOrder.createTime}</p>
            </div>

            <div style={{ marginTop: 24 }}>
              <h3>商品清单</h3>
              <Table
                dataSource={selectedOrder.items}
                rowKey="productId"
                pagination={false}
                columns={[
                  {
                    title: '商品名称',
                    dataIndex: 'productName',
                    key: 'productName',
                  },
                  {
                    title: '数量',
                    dataIndex: 'quantity',
                    key: 'quantity',
                  },
                  {
                    title: '单价',
                    dataIndex: 'price',
                    key: 'price',
                    render: (price: number) => `¥${price.toFixed(2)}`,
                  },
                  {
                    title: '小计',
                    key: 'subtotal',
                    render: (_, record) =>
                      `¥${(record.price * record.quantity).toFixed(2)}`,
                  },
                ]}
              />
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement; 